import mqtt from '../../../utils/mqtt.min.js'; //加载mqtt库
import * as comm from '../../../utils/common'; //加载mqtt库
const storageService = require('../../../services/storage')

const errEnum = {
  12000: '未先调用 startWifi 接口',
  12001: '当前系统不支持相关能力',
  12002: '密码错误',
  12003: '连接超时, 仅 Android 支持',
  12004: '重复连接 Wi-Fi',
  12005: 'Android 特有，未打开 Wi-Fi 开关',
  12006: 'Android 特有，未打开 GPS 定位开关',
  12007: '用户拒绝授权链接 Wi-Fi',
  12008: '无效 SSID',
  12009: '系统运营商配置拒绝连接 Wi-Fi',
  12010: '系统其他错误，需要在 errmsg 打印具体的错误原因',
  12011: '应用在后台无法配置 Wi-Fi',
  12013: '系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试，仅 Android 支持',
  12014: 'iOS 特有，无效的 WEP / WPA 密码'
}
const appInstance = getApp();
Page({
  data: {
    deviceId: '',
    deviceName: '',
    isFreshwater: false,
    isDIY: false, // 添加DIY标识
    deviceType: '', // 添加设备类型字段
    wifiName: '',
    password: '',
    showWifiNamePlaceholder: true,
    showWifiPasswordPlaceholder: true,
    isConfiguring: false,
    configSuccess: false,
    configFail: false,
    errorMsg: '',
    wifiList: [], // 可用的WiFi列表
    showWifiList: false, // 是否显示WiFi列表
    configStepMsg: "",
    devicePaswd: "12345678",
    deviceIp: "192.168.1.80",
    devicePort: 8266,
    deviceId: null,
    deviceVer: null,
    topicSend: null,
    topicSub: null,
    channels: [],
    fanStart: 40,
    pwopen: false, //是否显示密码
  },
  sendRertyTimes: 5,
  connDevice: false,
  sendUdp: false,
  waitMtTimes: 10,
  inited: false,
  onLoad: function (options) {
    // 获取从搜索页面传递过来的设备信息
    if (options) {
      // 解码 URL 参数
      //const deviceId = options.deviceId ? decodeURIComponent(options.deviceId) : '';
      //const bssid = options.bssid ? decodeURIComponent(options.bssid) : '';
      const ssid = options.ssid ? decodeURIComponent(options.ssid) : '';
      const isFreshwater = options.isFreshwater === 'true';
      const displayName = options.displayName ? decodeURIComponent(options.displayName) : '';
      const deviceType = options.deviceType ? decodeURIComponent(options.deviceType) :
        (isFreshwater ? 'freshwater_lamp' : 'seawater_lamp'); // 默认值

      // 检查是否为DIY设备
      const isDIY = deviceType === 'freshwater_diy_lamp' || deviceType === 'seawater_diy_lamp' || deviceType === 'orig_diy_lamp';
      //const signal= options.signal;

      console.log('接收到的参数:', {
        //deviceId,
        //bssid,
        ssid,
        isFreshwater,
        displayName,
        deviceType,
        isDIY
      }); // 调试信息

      /*const wifiList = [
        { SSID: ssid, secure: true, signalStrength: signal }
      ];*/
      this.setData({
        // 使用新的设备ID
        //deviceId: deviceId,
        // 使用自定义的显示名称，如果不存在则使用原始的设备ID
        deviceName: displayName || ssid,
        isFreshwater: isFreshwater,
        isDIY: isDIY, // 设置DIY标识
        deviceType: deviceType, // 设置设备类型
        // 保存BSSID和SSID供后续使用
        //bssid: bssid,
        ssid: ssid,
        //wifiName: ssid,
        showWifiNamePlaceholder: false,
        showWifiList: false // 立即隐藏列表和遮罩层
        //wifiList: wifiList
      });

      // 模拟获取附近WiFi列表
      //this.getWifiList();

      this.getConnectedWifi();
    }
  },

  onUnload: function () {
    // 页面卸载时清除定时器
  },

  // 获取WiFi列表
  /*getWifiList: function() {
    // 模拟获取WiFi列表
    const mockWifiList = [
      { SSID: 'WiFi_Home', secure: true, signalStrength: 4 },
      { SSID: 'WiFi_Office', secure: true, signalStrength: 3 },
      { SSID: 'Public_WiFi', secure: false, signalStrength: 2 },
      { SSID: 'Neighbor_5G', secure: true, signalStrength: 1 },
    ];
    
    this.setData({
      wifiList: mockWifiList
    });
  },*/

  // 输入WiFi名称
  inputWifiName: function (e) {
    this.setData({
      wifiName: e.detail.value,
    });
  },

  // 输入WiFi密码
  inputWifiPassword: function (e) {
    this.setData({
      password: e.detail.value,
    });
  },

  // WiFi名称输入框获取焦点
  onWifiFocus: function () {
    // 只处理占位符，列表显示由 toggleWifiList 控制
    /*this.setData({
      showWifiNamePlaceholder: false
    });*/
  },

  // WiFi名称输入框失去焦点
  onWifiBlur: function () {
    // 使用 setTimeout 延迟处理，给 selectWifi 执行留出时间
    setTimeout(() => {
      // 检查列表是否仍然显示（即 selectWifi 没有被调用来隐藏它）
      /*if (this.data.showWifiList) {
        this.setData({
          showWifiList: false // 如果列表还显示，则隐藏它
        });
      }*/
      // 检查输入框是否为空，如果为空则显示占位符
      if (!this.data.wifiName) {
        this.setData({
          showWifiNamePlaceholder: true
        });
      }
    }, 150); // 稍微增加延迟
  },

  // 选择WiFi列表中的WiFi
  selectWifi: function (e) {
    /*const ssid = e.currentTarget.dataset.ssid;
    this.setData({
      wifiName: ssid,
      showWifiNamePlaceholder: false,
      showWifiList: false // 立即隐藏列表和遮罩层
    });*/
  },

  // WiFi密码输入框获取焦点
  onPasswordFocus: function () {
    this.setData({
      showWifiPasswordPlaceholder: false,
    });
  },

  // WiFi密码输入框失去焦点
  onPasswordBlur: function () {
    if (!this.data.password) {
      this.setData({
        showWifiPasswordPlaceholder: true,
      });
    }
  },

  // 开始配网
  startConfig: function () {
    // 表单验证
    if (!this.data.wifiName.trim()) {
      wx.showToast({
        title: '请输入WiFi名称',
        icon: 'none',
      });
      return;
    }

    // 开始配网
    this.setData({
      isConfiguring: true,
      configSuccess: false,
      configFail: false,
      configStepMsg: "开始连接设备Wifi"
    });
    this.waitMtTimes = 10;
    this.sendRertyTimes = 5;

    // 模拟向ESP32设备发送WiFi配置信息
    console.log('正在向设备发送WiFi配置信息：', {
      ssid: this.data.wifiName,
      password: this.data.password,
      deviceId: this.data.deviceId
    });

    this.connectEsp();


    /*
    const configTimeoutVal = 3000; // 配网超时时间(ms)

    // 模拟配网过程
    const timeoutId = setTimeout(() => {
      // 随机模拟成功或失败
      const isSuccess = Math.random() > 0.3; // 70%概率成功

      if (isSuccess) {
        this.setData({
          isConfiguring: false,
          configSuccess: true,
          configTimeout: null
        });
      } else {
        this.setData({
          isConfiguring: false,
          configFail: true,
          errorMsg: '配网失败，请检查WiFi密码是否正确',
          configTimeout: null
        });
      }
    }, configTimeoutVal);

    // 保存定时器ID，以便在页面卸载时清除
    this.setData({
      configTimeout: timeoutId
    });
    */
  },

  // 重新配网
  retryConfig: function () {
    this.setData({
      configFail: false,
      errorMsg: '',
    });
  },

  // 完成配网，返回首页并添加新设备
  finishConfig: function () {
    // 创建新设备对象
    const newDevice = {
      id: this.data.deviceId, // 使用新的设备ID格式
      name: this.data.deviceName,
      deviceType: this.data.deviceType, // 使用设备类型字段
      status: '在线',
      power: true,
      startTime: '--:--',
      endTime: '--:--',
      temperature: this.data.fanStart, // 淡水设备和海水设备默认温度
      wifi: true,
      bluetooth: false,
      fan: false,
      red: 0,
      green: 0,
      blue: 0,
      white: 0,
      ssid: this.data.ssid, // 保存原始SSID
      bssid: this.data.bssid, // 保存BSSID
      isDIY: this.data.isDIY // 保存DIY标识
    };

    // 通过缓存传递新设备信息
    const newDeviceStr = JSON.stringify(newDevice);
    try {
      wx.setStorageSync('newDeviceInfo', newDeviceStr);
    } catch (e) {
      appInstance.logErr("存储空间已满，无法添加新设备", e)
      wx.showToast({
        title: '存储空间已满，无法添加新设备',
        icon: 'none',
        duration: 2000,
      });
      return;
    }

    // 返回首页
    // 添加一个小延时，尝试避免页面销毁时 autofill 相关的错误
    setTimeout(() => {
      wx.reLaunch({
        url: '/pages/index/index',
      });
    }, 100); // 100毫秒的延时
  },

  // --- New function to toggle WiFi list ---
  toggleWifiList: function () {
    /*this.setData({
      showWifiList: !this.data.showWifiList
    });*/
  },
  // ----------------------------------------
  getConnectedWifi() {
    wx.startWifi({
      success: (res1) => {
        console.log('WiFi模块已启用...');
        wx.getConnectedWifi({
          partialInfo: true,
          success: (res2) => {
            this.setData({
              wifiName: res2.wifi.SSID
            });
          },
          fail: (err2) => {
            appInstance.logErr("获取Wifi名称失败，请确认已连接Wifi！或者手动输入Wifi名称！", err2)
            this.showMsg("获取Wifi名称失败，请确认已连接Wifi！或者手动输入Wifi名称！" + JSON.stringify(err2));
          },
          complete: () => {
            wx.stopWifi();
            console.log("stopWifi...")
          }
        });
      },
      fail: (err1) => {
        appInstance.logErr("启用Wifi失败，请确认Wifi已开启！或者手动输入Wifi名称！", err1)
        this.showMsg("启用Wifi失败，请确认Wifi已开启！或者手动输入Wifi名称！");
      }

    });
  },
  showMsg(str) {
    wx.showModal({
      content: str,
      showCancel: false
    });
  },
  connectEsp() {
    const $t = this;
    $t.startWifi().then(res => {
      $t.connectWifi().then(res => {
        //connect udp
        setTimeout(function () {
          $t.connectUDP();
          setTimeout(function () {
            $t.sendDataUDP();
          }, 1000);
        }, 1000);
      });
    }).catch(err => {
      appInstance.logErr("connectEsp error ", err)
      console.log(err);
      $t.showMsg("启用Wifi失败！");
      $t.setData({
        isConfiguring: false,
        configFail: true,
        errorMsg: '启用Wifi失败'
      });
    });

  },
  async startWifi() {
    const cRes = await new Promise((resolve, reject) => {
      wx.startWifi({
        success: (res) => {
          resolve(res)
          return cRes
        },
        fail: (err) => {
          reject(err)
        }
      })
    });
  },
  async connectWifi() {
    const $t = this
    const cRes = await new Promise((resolve, reject) => {
      console.log("开始连接wifi。。。");
      // 连接wifi
      wx.connectWifi({
        SSID: $t.data.ssid,
        forceNewApi: true,
        password: $t.data.devicePaswd,
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          appInstance.logErr("connectWifi err", err, $t.data.ssid, $t.data.devicePaswd)
          console.log(err);
          if (err.errCode && err.errCode == 12005) {
            wx.showModal({
              content: '请先打开手机 Wi-Fi 开关',
              showCancel: false
            });
          } else {
            let errMsg = ''
            if (!err.errCode) {
              errMsg = err.errMsg
            } else {
              errMsg = errEnum[err.errCode]
            }
            wx.showModal({
              content: errMsg,
              showCancel: false
            });
            $t.setData({
              isConfiguring: false,
              configFail: true,
              errorMsg: errMsg
            });
          }
          reject(err)
        }
      })
    });
    return cRes
  },
  connectUDP() {
    this.setData({
      configStepMsg: "正在将WiFi信息发送至设备"
    });
    // 建立udp连接
    console.log("connectUDP...");
    const $t = this
    this.udp = wx.createUDPSocket()
    if (this.udp === null) {
      console.log('暂不支持');
      this.setData({
        isConfiguring: false,
        configFail: true,
        errorMsg: "设备通讯异常"
      });
      return;
    }
    this.udp.bind()
    this.udp.onListening(function (res) {
      console.log('监听中Res ===' + res)
    })
    this.udp.onMessage(res3 => {
      console.log(res3);
      const unit8Arr = new Uint8Array(res3.message)
      let encodedString = String.fromCharCode.apply(null, unit8Arr);
      encodedString = decodeURIComponent(escape((encodedString))); //没有这一步中文会乱码
      console.log(encodedString);
      let resObj = JSON.parse(encodedString);
      if (!resObj) {
        return;
      }
      if (resObj["cmdType"] === 4) {
        console.log(resObj["list"])
        wx.showModal({
          title: '连接提示',
          content: `当前选择的Wifi[${this.data.wifiName}]非2.4G网络，请重新选择Wifi!`,
          showCancel: false,
          success: function (res) {}
        });
        this.sendRertyTimes = -1
        this.setData({
          isConfiguring: false,
          configFail: true,
          errorMsg: "当前选择Wifi非2.4G"
        });
        return;
      }
      if (!(resObj["cmdType"] === 2 && resObj["topicSend"] && resObj["topicSub"] && resObj["deviceId"])) {
        return;
      }
      $t.data.deviceId = resObj["deviceId"];
      $t.data.deviceVer = resObj["deviceVer"];
      $t.data.topicSend = resObj["topicSend"];
      $t.data.topicSub = resObj["topicSub"];
      $t.data.channels = resObj["channels"];
      $t.data.eabCh = resObj["eabCh"];
      $t.data.eabTemp = resObj["eabTemp"];
      if (resObj["fanStart"]) {
        $t.data.fanStart = resObj["fanStart"];
      }
      $t.sendRertyTimes = 0;
      $t.sendUdp = true;

      $t.udp.send({
        address: $t.data.deviceIp,
        port: $t.data.devicePort,
        message: JSON.stringify({
          "cmdType": 3
        })
      });

      /*let deviceVer = resObj["deviceVer"];
      if (deviceVer != null && deviceVer.length > 1) {
        deviceVer = deviceVer.substring(1);
        var arr = deviceVer.split("_");
        var v1 = parseInt(arr[0].replace(".", ""));
        var v2 = arr.length > 1 ? parseInt(arr[1]) : 0;
        if ((v1 > 12 && v1 < 50) || (v1 > 50) || (v1 == 50 && v2 > 1)) {
          
        }
      }*/
      setTimeout(function () {
        $t.udp.close();
        $t.addDeviceSucc();
      }, 50);
      if ($t.data.deviceVer != 'v1') {
        $t.saveCfg2Local();
      }
    })
    return
  },
  sendDataUDP() {
    console.log("sendDataUDP...");
    if (this.sendRertyTimes <= 0) {
      return
    }
    this.sendRertyTimes--;
    const $t = this
    //this.content = '正在配网……'
    // 这是发送密码的内容。要维护一个定时器，如果每两秒不回复，那么要再发
    const msgData = {
      "cmdType": 1,
      "ssid": this.data.wifiName,
      "password": this.data.password,
      "uid": appInstance.globalData.openid,
      "sid": appInstance.globalData.sid,
    }
    console.log("send msg ..." + this.sendRertyTimes)
    this.udp.send({
      address: $t.data.deviceIp,
      port: $t.data.devicePort,
      message: JSON.stringify(msgData)
    })
    // 如果times==0，那么不需要再重试
    if (this.sendRertyTimes > 0) {
      setTimeout(() => {
        $t.sendDataUDP()
      }, 2000)
    } else {
      console.log("connect device fail");
      this.setData({
        isConfiguring: false,
        configFail: true,
        errorMsg: "设备通讯异常"
      });
    }
    return
  },
  addDeviceSucc() {
    const $t = this;
    $t.setData({
      configStepMsg: "等待设备连接"
    });
    console.log("start connect device ...");
    //设备激活
    if (appInstance.globalData.isRelease) {
      storageService.setActiveIds($t.data.deviceId)
    }
    wx.stopWifi();
    $t.mqttConnect();
  },
  mqttConnect() {
    const $t = this;
    //MQTT连接的配置
    var options = {
      keepalive: 10, //60s ，表示心跳间隔
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4, //MQTT v3.1.1
      connectTimeout: 10000,
      clientId: appInstance.globalData.mtid,
      username: appInstance.globalData.username,
      password: appInstance.globalData.password
    }
    //初始化mqtt连接
    console.log('开始连接服务器...' + new Date());
    $t.data.client = mqtt.connect(appInstance.globalData.mtaddr, options)
    // 连接mqtt服务器
    $t.data.client.on('connect', function () {
      console.log('连接服务器成功...' + new Date());
      $t.data.client.subscribe(appInstance.globalData.topicPre + $t.data.topicSub, function (err) {
        if (err) {
          $t.sendMtMsgFail();
          console.log(err);
          $t.showMsg("连接服务器异常(M)");
        }
      });
      $t.sendMtMsg();
    });
    //接收消息
    $t.data.client.on('message', function (topic, message) {
      console.log(topic + ":" + message);
      let resObj = JSON.parse(message);
      if (resObj != null && resObj["type"] == "init") {
        console.log("add device succ");
        if ($t.inited) {
          return;
        }
        $t.inited = true;
        $t.setData({
          isConfiguring: false,
          configSuccess: true
        });
        clearInterval($t.intervalObj);
        $t.intervalObj = null;
        $t.data.client.end(true);
        if ($t.data.deviceVer == 'v1') {
          $t.saveCfg2Local();
        }
        setTimeout(() => {
          let did = $t.data.deviceId;
          //跳转到首页
          wx.navigateTo({
            url: '/pages/index/index?did=' + did,
            fail: function (res) {
              console.log(res);
            }
          });
        }, 1000);
      }
    });
    //断线重连
    $t.data.client.on("reconnect", function () {
      console.log("重新连接")
    });
    $t.data.client.on("error", function (error) {
      console.log(error);
    });
  },
  sendMtMsg() {
    if (this.intervalObj != null) {
      return;
    }
    const $t = this;
    this.intervalObj = setInterval(() => {
      console.log("sendMtMsg:" + $t.waitMtTimes);
      if ($t.inited) {
        clearInterval($t.intervalObj);
        $t.intervalObj = null;
        return;
      }
      if ($t.data.deviceVer == "v1") {
        $t.data.client.publish(appInstance.globalData.topicPre + $t.data.topicSend, '{"type":"init"}');
      }
      $t.waitMtTimes--;
      if ($t.waitMtTimes <= 0) {
        $t.sendMtMsgFail();
      }
    }, 2000);
  },
  sendMtMsgFail() {
    this.setData({
      isConfiguring: false,
      configFail: true,
      errorMsg: "等待设备连接异常"
    });
    clearInterval(this.intervalObj);
    this.intervalObj = null;
    this.data.client.options.reconnectPeriod = 0;
    this.data.client.end(true);
    this.data.client = null;
  },
  saveCfg2Local() {
    const $t = this;
    setTimeout(() => {
      //添加到设备列表
      let did = $t.data.deviceId;
      let chs = $t.data.channels;
      for (var i = 0; i < chs.length; i++) {
        chs[i].u = 1;
      }
      storageService.saveDeviceChannels(did, chs)
      let deviceObj = {
        deviceId: did,
        deviceVer: $t.data.deviceVer,
        topicSend: $t.data.topicSend,
        topicSub: $t.data.topicSub,
        eabCh: $t.data.eabCh,
        eabTemp: $t.data.eabTemp,
        name: $t.data.deviceName,
        deviceType: $t.data.deviceType,
        isDIY: $t.data.isDIY
      }
      storageService.saveDeviceInfo(did, deviceObj)
      let dids = storageService.getDeviceIds()
      let exists = false;
      for (var i = 0; i < dids.length; i++) {
        if (dids[i] == did) {
          exists = true;
          break;
        }
      }
      if (!exists) {
        dids.push(did);
        storageService.saveDeviceIds(dids)
      }
      appInstance.initVerInfo(did, $t.data.deviceVer);
    }, 1000);

  },
  switch () { //是否显示密码
    this.setData({
      pwopen: !this.data.pwopen
    })
  },






});